package com.dly.blog.plugin;

import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.dly.blog.domain.File;
import com.dly.blog.enums.FileState;
import com.dly.blog.enums.UploadType;
import com.dly.blog.exception.FileExceptionEnum;
import com.dly.blog.properties.UploadProperties;
import com.dly.blog.utile.JwtService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.jni.FileInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import static org.bouncycastle.asn1.iana.IANAObjectIdentifiers.directory;

/**
 * @Author: DaiLiYu
 * @Date: 2023/7/12 22:18
 */
@Component
@Slf4j
@AllArgsConstructor
public class LocalUploadFile implements UploadFilePlugin{

    private final UploadProperties uploadProperties;

    private final Sequence sequence = new Sequence(null);

    private final JwtService jwtService;

    @Override
    public File uploadFile(File fileInfo , String filePath, MultipartFile multipartFile) {
        try {
            upload(fileInfo, filePath, multipartFile);
            fileInfo.setUrl(uploadProperties.getLocal().getImagePath()+ fileInfo.getId());
        }catch (Exception e){
            log.info("上传失败 {}", e.getMessage());
            throw FileExceptionEnum.FILE_UPLOAD_ERROR.getFileException();
        }
        return fileInfo;
    }

    public void upload(File fileInfo , String filePath, MultipartFile multipartFile) throws IOException {
        long fileId = sequence.nextId();
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new java.io.File(uploadProperties.getLocal().getRootPath()+filePath + StringPool.SLASH + fileId));
        fileInfo.setFilePath(uploadProperties.getLocal().getRootPath() + filePath + fileId);
        fileInfo.setId(String.valueOf(fileId));
        fileInfo.setFileState(FileState.EFFECTIVE);
    }

    @Override
    public File uploadFileTerm(File fileInfo, String filePath, MultipartFile multipartFile) {
        try {
            upload(fileInfo, filePath, multipartFile);
            //通过jwt 加密授权 一个token
            String token = jwtService.signFile(fileInfo.getId(), fileInfo.getExpirationDate());
            fileInfo.setUrl(uploadProperties.getLocal().getImagePrivatePath() + token);
        }catch (Exception e){
            log.info("上传失败 {}", e.getMessage());
            throw FileExceptionEnum.FILE_UPLOAD_ERROR.getFileException();
        }
        return fileInfo;
    }

    @Override
    public boolean supports(UploadType delimiter) {
        return delimiter.equals(UploadType.LOCAL);
    }
}
